<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="验车时间" prop="checkTime">
        <el-date-picker clearable
                        v-model="queryParams.checkTime"
                        :valueFormat="'yyyy-MM-dd HH:mm:ss'"
                        type="datetime"
                        default-time="12:00:00"
                        placeholder="请选择验车时间">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="验车状况" prop="checkMark">-->
<!--        <el-input-->
<!--          v-model="queryParams.checkMark"-->
<!--          placeholder="请输入验车状况"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:check:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:check:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:check:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="${comment}" align="center" prop="id" />-->
      <el-table-column label="车辆编号" align="center" prop="carId" />
      <el-table-column label="验车时间" align="center" prop="checkTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.checkTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="验车状况" align="center" prop="checkMark" />
      <el-table-column prop="fileImgList" label="验车图片" width="220">
        <template slot-scope="scope">
          <a @click="showImage()"><div class="moreImg" :class="{'moreImg':scope.row.fileImgList.length > 1}" >
            <el-image class="itemImg" v-for="(item , index) in scope.row.fileImgList" :key="index" :src="item.url" :fit="fit"></el-image>
          </div></a>
          <el-dialog title="图片预览"
                     :visible.sync="dialogImgs"
                     width="550">
            <el-carousel :autoplay="false">
              <el-carousel-item v-for="(item,index) in scope.row.fileImgList" :key="item" style="text-align:center;">
                <h2 style="text-align:center;">{{index+1}}-{{scope.row.fileImgList.length}}</h2>
                <img :src="item.url" alt="" style="height:100%;width:100%;object-fit: contain;" />
              </el-carousel-item>
            </el-carousel>
          </el-dialog>
        </template>
      </el-table-column>
      <el-table-column label="验车视频" prop="checkVideo" width="220">
        <template slot-scope="scope">
          <div class="moreImg" :class="{'moreImg':scope.row.fileVideoList.length > 1}" >
            <a @click="showVideo(item)" v-for="(item , index) in scope.row.fileVideoList" :key="index">
              <video class="itemVideo" :src="item.url"></video>
            </a>
          </div>
          <el-dialog title="验车视频"
                     :visible.sync="dialogVideo"
                     width="550" @close="onCloseVideo">
            <video :src="dialogVideoUrl" controls class="video" ref="vueRef"
                   style="width: 100%;max-height: 600px;object-fit: contain;">您的浏览器不支持视频播放</video>
          </el-dialog>
        </template>
      </el-table-column>
<!--      <el-table-column label="${comment}" align="center" prop="createUserid" />-->
<!--      <el-table-column label="${comment}" align="center" prop="updateUserid" />-->
<!--      <el-table-column label="1全款控车前2发车前3到货时4物流目的地自提54S店自提" align="center" prop="status" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车辆编号" prop="carId">
          <el-input v-model="form.carId" placeholder="请输入验车状况" />
        </el-form-item>
        <el-form-item label="验车时间" prop="checkTime">
          <el-date-picker clearable
            v-model="form.checkTime"
                          :valueFormat="'yyyy-MM-dd HH:mm:ss'"
            type="datetime"
                          default-time="12:00:00"
            placeholder="请选择验车时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="验车状况" prop="checkMark">
          <el-input v-model="form.checkMark" type="textarea" placeholder="请输入验车状况" />
        </el-form-item>
        <el-form-item label="验车图片" prop="fileImgList">
          <el-upload
            action="/ossfile/file/common/uploadImg"
            :data="uploadData"
            :headers="headerObj"
            :auto-upload="true"
            ref="refName"
            :file-list="form.fileImgList"
            accept="image/jpeg,image/gif,image/png"
            :on-success="handleAvatarSuccess"
            :before-upload="onBeforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传图片格式文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="验车视频" prop="checkVideo">
          <el-upload
            action="/ossfile/file/common/uploadImg"
            :data="uploadData"
            :headers="headerObj"
            ref="refVideoName"
            :file-list="form.fileVideoList"
            :on-success="handleAvatarVideoSuccess"
            :before-upload="onBeforeVideoUpload"
            :on-preview="handlePictureCardVideoPreview"
            :on-remove="handleVideoRemove">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传视频格式文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img style="width: 100%;max-height: 600px;object-fit: contain;" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-dialog :visible.sync="dialogVideoVisible" @close="onCloseVideo">
      <video :src="dialogVideoUrl" controls class="video"
             style="width: 100%;max-height: 600px;object-fit: contain;" ref="vueRef">您的浏览器不支持视频播放</video>
    </el-dialog>
  </div>
</template>

<script>
import { listCheck, getCheck, delCheck, addCheck, updateCheck } from "@/api/system/check";
import { getToken } from '@/utils/auth';

export default {
  name: "Check",
  data() {
    return {
      headerObj: {
        Authorization: getToken()
      },
      dialogImgs: false,
      dialogVideo: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      uploadData: {
        status: "1",
        oldFilePath:""
      },
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogVideoUrl: '',
      dialogVideoVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        checkTime: null,
        checkMark: null,
        checkImg: null,
        checkVideo: null,
        createUserid: null,
        updateUserid: null,
        carId: null,
        status: 2
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    onCloseVideo(){
      if (!this.$refs.vueRef.paused){
        this.$refs.vueRef.pause();
      }
    },
    showImage(){
      this.dialogImgs = true;
    },
    showVideo(file){
      this.dialogVideo = true;
      this.dialogVideoUrl = file.url;
    },
    handleAvatarSuccess(response, file, fileList){   //上传成功后的回调函数
      console.log(response);
      console.log(file);
      console.log(fileList);
      if (response.code == 200){
        this.form.fileImgList.push({
          'name' : response.url.substring(response.url.lastIndexOf('/') + 1, response.url.lastIndexOf('.')),
          'url' : response.url
        });
      } else {
        this.$refs.refName.uploadFiles.splice(this.$refs.refName.uploadFiles.indexOf(file), 1);
      }
    },
    handleAvatarVideoSuccess(response, file, fileList){   //上传成功后的回调函数
      console.log(response);
      console.log(file);
      console.log(fileList);
      if (response.code == 200){
        this.form.fileVideoList.push({
          'name' : response.url.substring(response.url.lastIndexOf('/') + 1, response.url.lastIndexOf('.')),
          'url' : response.url
        });
      } else {
        this.$refs.refVideoName.uploadFiles.splice(this.$refs.refVideoName.uploadFiles.indexOf(file), 1);
      }
    },
    handleRemove(file, fileList) {
      console.log(file);
      console.log(fileList);
      this.form.fileImgList = fileList;
      if (this.form.fileImgList == null || this.form.fileImgList == undefined || this.form.fileImgList.length == 0) {

      } else {
        for (let i = 0; i < this.form.fileImgList.length; i++) {
          if (this.form.fileImgList[i].url == file.url){
            this.form.fileImgList.splice(i);
          }
        }
      }
    },
    handleVideoRemove(file, fileList) {
      console.log(file);
      console.log(fileList);
      this.form.fileVideoList = fileList;
      if (this.form.fileVideoList == null || this.form.fileVideoList == undefined || this.form.fileVideoList.length == 0) {

      } else {
        for (let i = 0; i < this.form.fileVideoList.length; i++) {
          if (this.form.fileVideoList[i].url == file.url){
            this.form.fileVideoList.splice(i);
          }
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardVideoPreview(file) {
      this.dialogVideoUrl = file.url;
      this.dialogVideoVisible = true;
    },
    onBeforeUpload(file) {
      const isIMAGE = file.type === 'image/jpeg'||'image/gif'||'image/png';
      // const isLt1M = file.size / 1024 / 1024 < 900;

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!');
      }
      // if (!isLt1M) {
      //   this.$message.error('上传文件大小不能超过 900MB!');
      // }
      // return isIMAGE && isLt1M;
      this.uploadData.status = 1;
      return isIMAGE
    },
    onBeforeVideoUpload(file) {
      // 获取视频时长
      var url = URL.createObjectURL(file);
      var audioElement = new Audio(url);
      var duration;
      this.durationNumber = audioElement.addEventListener(
        "loadedmetadata",
        function(_event) {
          duration = audioElement.duration; //时长为秒，小数
          return duration;
        }
      );
      setTimeout(() => {
        //视频大小（MB）
        let fileSize = file.size / 1024 / 1024;
        this.bandwidth = fileSize / duration;
      }, 50);
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
          "video/mov"
        ].indexOf(file.type) == -1
      ) {
        // layer.msg("请上传正确的视频格式");
        this.$message({
          type: "info",
          message: "请上传正确的视频格式"
        });
        return false;
      }
      if (this.bandwidth > 2) {
        // 视频带宽不能超过2MB/s
        this.$message.error('视频带宽过大，上传失败！');
        return false;
      }
      this.uploadData.status = 2;
      this.isShowUploadVideo = false;
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      this.queryParams.status = 2;
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        checkTime: null,
        checkMark: null,
        checkImg: null,
        fileImgList: [],
        fileVideoList: [],
        checkVideo: null,
        createUserid: null,
        updateUserid: null,
        createTime: null,
        updateTime: null,
        carId: null,
        status: 2
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCheck(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.status = 2;
            this.form.checkImg = "";
            if (this.form.fileImgList == null || this.form.fileImgList == undefined || this.form.fileImgList.length == 0) {
              this.form.checkImg = "";
            } else {
              for (let i = 0; i < this.form.fileImgList.length; i++) {
                if (this.form.checkImg == null || this.form.checkImg == undefined || this.form.checkImg == "") {
                  this.form.checkImg = this.form.fileImgList[i].url;
                } else {
                  this.form.checkImg = this.form.checkImg + "," + this.form.fileImgList[i].url;
                }
              }
            }

            this.form.checkVideo = "";
            if (this.form.fileVideoList == null || this.form.fileVideoList == undefined || this.form.fileVideoList.length == 0) {
              this.form.checkVideo = "";
            } else {
              for (let i = 0; i < this.form.fileVideoList.length; i++) {
                if (this.form.checkVideo == null || this.form.checkVideo == undefined || this.form.checkVideo == "") {
                  this.form.checkVideo = this.form.fileVideoList[i].url;
                } else {
                  this.form.checkVideo = this.form.checkVideo + "," + this.form.fileVideoList[i].url;
                }
              }
            }
            updateCheck(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.status = 2;
            this.form.checkImg = "";
            if (this.form.fileImgList == null || this.form.fileImgList == undefined || this.form.fileImgList.length == 0) {
              this.form.checkImg = "";
            } else {
              for (let i = 0; i < this.form.fileImgList.length; i++) {
                if (this.form.checkImg == null || this.form.checkImg == undefined || this.form.checkImg == "") {
                  this.form.checkImg = this.form.fileImgList[i].url;
                } else {
                  this.form.checkImg = this.form.checkImg + "," + this.form.fileImgList[i].url;
                }
              }
            }

            this.form.checkVideo = "";
            if (this.form.fileVideoList == null || this.form.fileVideoList == undefined || this.form.fileVideoList.length == 0) {
              this.form.checkVideo = "";
            } else {
              for (let i = 0; i < this.form.fileVideoList.length; i++) {
                if (this.form.checkVideo == null || this.form.checkVideo == undefined || this.form.checkVideo == "") {
                  this.form.checkVideo = this.form.fileVideoList[i].url;
                } else {
                  this.form.checkVideo = this.form.checkVideo + "," + this.form.fileVideoList[i].url;
                }
              }
            }
            addCheck(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delCheck(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/check/export', {
        ...this.queryParams
      }, `check_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
  .wrap {
      img {
        width: 100%;
        height: 100%;
      }
  }
  .moreImg{
      display: flex;
      flex-wrap: wrap;
    .itemImg{
      width: 25px;
      height: 25px;
      margin-right: 3px;
      margin-top: 3px;
    }
    .itemVideo{
      width: 55px;
      height: 55px;
      margin-right: 3px;
      margin-top: 3px;
    }
  }
</style>
